package toolkit

import (
	"os"
	"path"
	"path/filepath"
	"strings"
)

func FindFiles(dir string) ([]string, error) {
	return FindFilesWithPrefix(dir, "")
}

func FindFilesWithPrefix(dir, prefix string) ([]string, error) {
	filePaths, err := filepath.Glob(filepath.Join(dir, prefix+"*"))
	if err != nil {
		return nil, err
	}

	matchingFiles := make([]string, 0, len(filePaths))
	for _, filePath := range filePaths {
		file, err := os.Stat(filePath)
		if err != nil {
			return nil, err
		}

		if file.IsDir() {
			continue
		}

		_, fileName := filepath.Split(filePath)
		matchingFiles = append(matchingFiles, fileName)
	}
	return matchingFiles, nil
}

// FindFilesWithPrefix2 查找给定目录下具有相同文件名前缀的所有文件
func FindFilesWithPrefix2(dir, prefix string) ([]string, error) {
	files, err := os.ReadDir(dir)
	if err != nil {
		return nil, err
	}

	matchingFiles := make([]string, 0, len(files))
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		if prefix == "" || strings.HasPrefix(path.Base(file.Name()), prefix) {
			matchingFiles = append(matchingFiles, file.Name())
		}
	}

	return matchingFiles, nil
}
